package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.CommentDTO;
import com.sky.dto.CommentPageQueryDTO;
import com.sky.entity.Comment;
import com.sky.entity.ManageComment;
import com.sky.entity.User;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.CommentService;
import com.sky.utils.CommentConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private ManageBlogMapper manageBlogMapper;
    @Autowired
    private ManageCommentMapper manageCommentMapper;


    /**
     * 根据博客id查找评论
     * @param commentPageQueryDTO
     * @return
     */
    public PageResult getByBlogId(CommentPageQueryDTO commentPageQueryDTO) {
        PageHelper.startPage(commentPageQueryDTO.getPage(),commentPageQueryDTO.getPageSize());
        Page<Comment> page =commentMapper.getByBlogIdParent(commentPageQueryDTO);
        long total = page.getTotal();
        List<Comment> comments = page.getResult();
        List<Long> parentIds = comments.stream()
                .map(Comment::getId)
                .collect(Collectors.toList());
        if (parentIds.size() > 0) {
        List<Comment> childrenComments = commentMapper.getChildernComments(parentIds);
        comments.addAll(childrenComments);}
        return new PageResult(total,comments);
    }

    /**
     * 增加评论
     * @param commentDTO
     */
    public void insertComment(CommentDTO commentDTO) {
        Comment comment = new Comment();

        BeanUtils.copyProperties(commentDTO,comment);

        comment.setUserId(BaseContext.getCurrentId());
        User byId = userMapper.getById(comment.getUserId());
        comment.setUserName(byId.getUsername());
        comment.setImage(byId.getImage());


        blogMapper.addCommentCount(comment.getBlogId());
        String id= String.valueOf(comment.getBlogId());
        manageBlogMapper.addCommentCount(id);
        commentMapper.insert(comment);
        ManageComment manageComment = CommentConverter.fromComment(comment);
        manageCommentMapper.insert(manageComment);

    }
}
